package short_semester.questionnaire_planet.controller;

import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import short_semester.questionnaire_planet.dao.QuestionnaireDao;
import short_semester.questionnaire_planet.dao.QuestionnaireRecordDao;
import short_semester.questionnaire_planet.dao.UserDao;
import short_semester.questionnaire_planet.entity.User;
import short_semester.questionnaire_planet.pojo.Questionnaire;
import short_semester.questionnaire_planet.pojo.QuestionnaireRecord;
import short_semester.questionnaire_planet.receiver.CheckboxReceiver;
import short_semester.questionnaire_planet.request.fillRequest.ip.IPBody;
import short_semester.questionnaire_planet.request.fillRequest.ip.SubmitBody;
import short_semester.questionnaire_planet.response.CommonResponse;
import short_semester.questionnaire_planet.service.analyse.*;

import java.util.Optional;

@RestController
@RequestMapping("/api")
public class FillInController {


    @Autowired
    QuestionnaireRecordService questionnaireRecordService;

    @Autowired
    SingleChoiceQuestionRecordService singleChoiceQuestionRecordService;

    @Autowired
    MultipleChoiceQuestionRecordService multipleChoiceQuestionRecordService;

    @Autowired
    FillBlankQuestionRecordService fillBlankQuestionRecordService;

    @Autowired
    ScoreQuestionRecordService scoreQuestionRecordService;
    
    @Autowired
    UserDao userDao;

    @Autowired
    QuestionnaireRecordDao questionnaireRecordDao;

    @Autowired
    QuestionnaireDao questionnaireDao;

    @PostMapping("/fill/submitRadio")
    public CommonResponse submitRadio(
            @RequestParam("questionnaireId") Integer questionnaireId,
            @RequestParam("questionId") Integer questionId,
            @RequestParam("id") String id,
            @RequestParam("optionId") Integer optionId,
            @RequestParam("uuid") String uuid
    ) {
        CommonResponse cr = new CommonResponse();
        QuestionnaireRecord  questionnaireRecord;
        try {
            Integer userId = null;
            if(id==null||id.isEmpty()){
                userId = null;
            }else{
                userId = Integer.parseInt(id);
            }
            questionnaireRecord =  questionnaireRecordService.checkExistence(userId, questionnaireId, uuid);
        } catch (Exception e) {
            cr.setCode(1);
            cr.setMsg(e.getMessage());
            return cr;
        }
        singleChoiceQuestionRecordService.addRecord(questionId, questionnaireRecord, optionId);
        cr.setCode(0);
        cr.setMsg("Success");
        return cr;
    }

    @PostMapping("/fill/submitCheckBox")
    public CommonResponse submitCheckBox(
           @RequestBody CheckboxReceiver param
    ) {
        CommonResponse cr = new CommonResponse();
        QuestionnaireRecord  questionnaireRecord;
//        System.out.println(param.getOptions());
        try {
            Integer userId = null;
            if(param.getId()==null||param.getId().isEmpty()){
                userId = null;
            }else{
                userId = Integer.parseInt(param.getId());
            }
            questionnaireRecord =  questionnaireRecordService.checkExistence(
                    userId, param.getQuestionnaireId(), param.getUuid());
        } catch (Exception e) {
            cr.setCode(1);
            cr.setMsg(e.getMessage());
            return cr;
        }
        multipleChoiceQuestionRecordService.addRecord(param.getQuestionId(), questionnaireRecord, param.getOptions());
        cr.setCode(0);
        cr.setMsg("Success");
        return cr;
    }


    @PostMapping("/fill/submitCompletion")
    public CommonResponse submitCompletion (
            @RequestParam("questionnaireId") Integer questionnaireId,
            @RequestParam("questionId") Integer questionId,
            @RequestParam("id") String id,
            @RequestParam("content") String content,
            @RequestParam("uuid") String uuid
    ) {
        CommonResponse cr = new CommonResponse();
        QuestionnaireRecord  questionnaireRecord;
        try {
            Integer userId = null;
            if(id==null||id.isEmpty()){
                userId = null;
            }else{
                userId = Integer.parseInt(id);
            }
            questionnaireRecord =  questionnaireRecordService.checkExistence(userId, questionnaireId, uuid);
        } catch (Exception e) {
            cr.setCode(1);
            cr.setMsg(e.getMessage());
            return cr;
        }
        fillBlankQuestionRecordService.addRecord(questionId, questionnaireRecord, content);
        cr.setCode(0);
        cr.setMsg("Success");
        return cr;
    }

    @PostMapping("/fill/submitScore")
    public CommonResponse submitScore(
            @RequestParam("questionnaireId") Integer questionnaireId,
            @RequestParam("questionId") Integer questionId,
            @RequestParam("id") String id,
            @RequestParam("optionId") Integer optionId,
            @RequestParam("uuid") String uuid
    ) {
        CommonResponse cr = new CommonResponse();
        QuestionnaireRecord questionnaireRecord;
        try {
            Integer userId = null;
            if(id==null||id.isEmpty()){
                userId = null;
            }else{
                userId = Integer.parseInt(id);
            }
            questionnaireRecord = questionnaireRecordService.checkExistence(userId, questionnaireId, uuid);
        } catch (Exception e) {
            cr.setCode(1);
            cr.setMsg(e.getMessage());
            return cr;
        }
        scoreQuestionRecordService.addRecord(questionId, questionnaireRecord, optionId);
        cr.setCode(0);
        cr.setMsg("Success");
        return cr;
    }

    @PostMapping("/fill/userSubmit")
    public CommonResponse userSubmit(@RequestBody SubmitBody body) {
        String userId = body.getId();
        String uuid = body.getUuid();
        Integer questionnaireId = body.getQuestionnaireId();
        IPBody ipBody = body.getIpBody();
        
        String type = body.getType();
        
        CommonResponse cr = new CommonResponse();
        Boolean isSubmitted;
        try {
            isSubmitted = isSubmitted(userId, questionnaireId, uuid);
        }catch (Exception e){
            e.printStackTrace();
            cr.error(e.getMessage());
            return cr;
        }
        
        if (isSubmitted) {
            cr.setCode(-1);
            cr.setMsg("用户已经提交过该问卷");
            return cr;
        }
        try {
            Integer id = null;
            if(userId!=null&&!userId.equals(""))
                id = Integer.parseInt(userId);
            Integer recordId = questionnaireRecordService.submit(id, questionnaireId,uuid,ipBody,type);
            cr.setData(recordId);
        } catch (Exception e) {
            e.printStackTrace();
            cr.setCode(1);
            cr.setMsg(e.getMessage());
            return cr;
        }
        cr.setCode(0);
        cr.setMsg("Success");
        return cr;
    }


    public Boolean isSubmitted(
            String userId,
            Integer questionnaireId,
            String uuid
    ) throws Exception {

        Boolean isSubmitted = false;
        Questionnaire questionnaire = questionnaireDao.getById(questionnaireId);
        if(userId!=null){
            //用户已登录
            User user = userDao.getById(Integer.parseInt(userId));
            Optional<QuestionnaireRecord> optional = questionnaireRecordDao.findByUserAndQuestionnaire(user, questionnaire);

            if(optional.isPresent()) {
                //有记录
                QuestionnaireRecord record = optional.get();
                isSubmitted = record.getIsSubmitted();
            }else{
                throw new Exception("该用户无权作答");
            }
        }else if(uuid!=null&&!uuid.isEmpty()){
            //临时用户
            Optional<QuestionnaireRecord> optional = questionnaireRecordDao.findByUuidAndQuestionnaire(uuid,questionnaire);
            if(optional.isPresent()){
                //有记录
                QuestionnaireRecord record = optional.get();
                isSubmitted = record.getIsSubmitted();
            }else {
                throw new Exception("该用户无权作答");
            }
        }else {
            throw new Exception("userId和uuid怎么都是空的!");
        }
        
        return isSubmitted;

    }
}
